package ch01;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestThreadPool {

	public static void main(String[] args) {
		
		// 创建线程数量固定为2线程池
		ExecutorService exec = Executors.newFixedThreadPool(2);
		
		// 创建100个线程目标对角
		for (int i = 0; i < 100; i++) {
			Runnable runnable = new Runner(i);
			exec.execute(runnable);
		}
		
		// shutdown
		exec.shutdown();
	}
}

class Runner implements Runnable{
	
	int index = 0;
	
	public Runner(int index){
		this.index = index;
	}
	
	@Override
	public void run(){
		long time = (long)(Math.random() * 1000);
		// 输出线程的名字和使用目标对象及休眠时间 
		System.out.println("线程：" + Thread.currentThread().getName() + "(目标对象" + this.index + ")" 
				+ "Sleeping " +  time  + "ms");
		try{
			Thread.sleep(time);
		}catch (InterruptedException e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}
	
}
